package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则Service业务层处理
 *
 * @author gzh
 * @date 2025-10-21
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private StringRedisTemplate redisTemplate; //注意要和你放数据用的RedisTemplate要一致

    @Override
    public void alertFilter() {


        //查询所有规则
        List<AlertRule> ruleList = this.list(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (CollUtil.isEmpty(ruleList)) {
            return;
        }
        //查询所有设备上报的数据
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        if (CollUtil.isEmpty(values)) {
            return;
        }


        List<DeviceData> deviceDataList = new ArrayList<>();
        //做格式化处理 把数据放到一个大集合中
        for (Object value : values) {

            List<DeviceData> deviceDataList1 = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.addAll(deviceDataList1);
        }

        //一条一条的数据处理
        for (DeviceData deviceData : deviceDataList) {
            //开始一条一条的处理
            System.out.println("--------" + deviceData);
            alterFilter(deviceData);
        }

    }

    int alertFilterCount;

    private void alterFilter(DeviceData deviceData) {


        log.info("进入到alterFilter方法的次数:" + alertFilterCount);
        alertFilterCount++;

        //举例:查询心率 对所有设备
        //产品key functuonId iotId -1
        LambdaQueryWrapper<AlertRule> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AlertRule::getProductKey, deviceData.getProductKey());
        queryWrapper1.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper1.eq(AlertRule::getIotId, -1);
        queryWrapper1.eq(AlertRule::getStatus, 1);
        List<AlertRule> ruleList1 = this.list(queryWrapper1);

        //举例:查询心率 指定设备  老秦的设备
        //产品key functuonId iotId  老秦的设备Id

        LambdaQueryWrapper<AlertRule> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(AlertRule::getProductKey, deviceData.getProductKey());
        queryWrapper2.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper2.eq(AlertRule::getIotId, deviceData.getIotId());
        List<AlertRule> ruleList2 = this.list(queryWrapper2);

        //合并两个集合
        Collection<AlertRule> ruleList = CollUtil.addAll(ruleList1, ruleList2);
        if (CollUtil.isEmpty(ruleList)) {
            return;
        }


        for (AlertRule alertRule : ruleList) {
            deviceDataAlarmHandler(alertRule, deviceData);
        }
    }

    @Autowired
    private ScriptEngine scriptEngine;

    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {

        log.info("开始第一层校验");
        String period = alertRule.getAlertEffectivePeriod();
        String[] periods = period.split("~");
        LocalTime startTime = LocalTime.parse(periods[0]);
        LocalTime endTime = LocalTime.parse(periods[1]);

        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();

        //alarmTime startTime endTime alarmTime
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            return;
        }

        String alertCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + deviceData.getIotId() + deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX + deviceData.getIotId() + deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();

        log.info("开始第二层的校验");

        String expresstion = deviceData.getDataValue() + alertRule.getOperator() + alertRule.getValue();


        Boolean isReach = false;
        try {
            isReach = (Boolean) scriptEngine.eval(expresstion);
        } catch (ScriptException e) {
            e.printStackTrace();
            isReach = false;
        }

        if (!isReach) {
            redisTemplate.delete(alertCountKey);  // 从0开始计算
            return;
        }

        log.info("开始第三层的校验");

        Boolean isHaveSlient = redisTemplate.hasKey(slientKey);

        if (isHaveSlient) { //有沉默周期
            return;
        }


        log.info("开始第四层的校验");
        //产品+设备+属性名 +规则
        Long alertCount = redisTemplate.boundValueOps(alertCountKey).increment();
        if (alertCount >= alertRule.getDuration()) {
            log.info("可以报警了.............................");
            redisTemplate.delete(alertCountKey);//删除报警次数  从0开始数数
            redisTemplate.boundValueOps(slientKey).set("", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);


            //插入报警数据
            insertAlertData(alertRule, deviceData);
        }
    }

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;//行政
    @Value("${alert.managerRole}")
    private String managerRole;//超级管理员

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IAlertDataService alertDataService;


    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {

        List<Long> userIds = new ArrayList<>();

        if (deviceData.getLocationType().equals(0)) {


            //根据老人找护理员
            List<Long> userId = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());


        } else {

            if (deviceData.getPhysicalLocationType().equals(1)) {
                //固定设备报警找行政
                //根据行政这个角色找人
                userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
            } else if (deviceData.getPhysicalLocationType().equals(2)) {
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }
        //查询超级管理员
        List<Long> adminIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);

        Collection<Long> collection = CollUtil.addAll(userIds, adminIds);

        userIds = CollUtil.distinct(collection);//去重

        List<AlertData> alertDataList =new ArrayList<>();

        for (Long userId : userIds) {

            AlertData alertData = new AlertData();
            alertData.setIotId(deviceData.getIotId());
            alertData.setDeviceName(deviceData.getDeviceName());
            alertData.setProductKey(deviceData.getProductKey());
            alertData.setProductName(deviceData.getProductName());
            alertData.setFunctionId(deviceData.getFunctionId());
            alertData.setAccessLocation(deviceData.getAccessLocation());
            alertData.setLocationType(deviceData.getLocationType());
            alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
            alertData.setDeviceDescription(deviceData.getDeviceDescription());
            alertData.setDataValue(deviceData.getDataValue());
            alertData.setAlertRuleId(alertRule.getId());
            alertData.setAlertReason(deviceData.getFunctionId() + alertRule.getOperator() + alertRule.getValue() + alertRule.getDuration() + alertRule.getAlertSilentPeriod());
//            alertData.setProcessingResult();
//            alertData.setProcessorId();
//            alertData.setProcessorName();
//            alertData.setProcessingTime();
            alertData.setType(deviceData.getLocationType());
            alertData.setStatus(0);
            alertData.setUserId(userId);

           alertDataList.add(alertData);
        }

        alertDataService.saveBatch(alertDataList);
        websocketNotity(alertDataList.get(0), alertRule, userIds);
    }
    @Autowired
    private WebSocketServer webSocketServer;
    private void websocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        //属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        //向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo,allUserIds);

    }
}
